package com.example.a2022application.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.a2022application.BaseActivity;
import com.example.a2022application.R;
import com.example.a2022application.bean.UploadBean;
import com.example.a2022application.net.Urls;
import com.example.a2022application.utils.DateUtil2;
import com.example.a2022application.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

public class SendTaskActivity extends BaseActivity implements View.OnClickListener {
    private TextView display_time;
    private ImageView img_add;
    private static int REQUEST_CODE_DOC = 1;
    private RelativeLayout rl_time;
    private String tid;

    private static final int REQUEST_EXTERNAL_STORAGE = 2;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.MANAGE_EXTERNAL_STORAGE"};
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sendtask);
        img_add = findViewById(R.id.img_add);
        rl_time = findViewById(R.id.rl_time);
        display_time = findViewById(R.id.display_time);
        rl_time.setOnClickListener(this);
        img_add.setOnClickListener(this);
        verifyStoragePermissions(this);

        Intent intent = getIntent();
        tid = intent.getStringExtra("oid");
    }
    public static void verifyStoragePermissions(Activity activity) {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_add:
                if (TextUtils.isEmpty(display_time.getText().toString())){
                    ToastUtil.showToast("请先选择截止时间");
                }else {
                    getDocument();
                }

                break;
            case R.id.rl_time:
                choiseTime();
                break;
        }
    }

    private void choiseTime() {
        int mYear;
        int mMonth;
        int mDay;
        Calendar nowdate = Calendar.getInstance();
        String birthday = display_time.getText().toString();
        if (TextUtils.isEmpty(birthday)) {
            mYear = nowdate.get(Calendar.YEAR);
            mMonth = nowdate.get(Calendar.MONTH);
            mDay = nowdate.get(Calendar.DAY_OF_MONTH);
        } else {
            mYear = Integer.valueOf(DateUtil2.getStringToYear(birthday, "yyyy-MM-dd"));
            mMonth = Integer.valueOf(DateUtil2.getStringToMonth(birthday, "yyyy-MM-dd"));
            mDay = Integer.valueOf(DateUtil2.getStringToDay(birthday, "yyyy-MM-dd"));
        }

        new DatePickerDialog(SendTaskActivity.this, onDateSetListener, mYear, mMonth, mDay+7).show();

    }

    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            int mYear = year;
            int mMonth = monthOfYear + 1;
            int mDay = dayOfMonth;
            String days;
            days = new StringBuffer().append(mYear).append("-").append(mMonth).append("-").append(mDay).toString();
            display_time.setText(days);
        }
    };

    private void getDocument() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/msword,application/pdf");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
        startActivityForResult(intent, REQUEST_CODE_DOC);
    }

    @Override
    protected void onActivityResult(int req, int result, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(req, result, data);
        Log.e("tag","result--"+result);
        if (result == RESULT_OK)
        {
            Uri fileuri = data.getData();
            String docFilePath = getFileNameByUri(this, fileuri);
            File file = new File(docFilePath);

            Log.e("tag","file----"+file.exists());
            List<File> files = new ArrayList();
            files.add(file);
            OkGo.<String>post(Urls.UPLOAD)
                    .isMultipart(true)
                    .params("endtime",display_time.getText().toString())
                    .params("timetable_id",tid)
                    .addFileParams("file", files)
                    .execute(new StringCallback() {

                        @SuppressLint("LongLogTag")
                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.e("TAG", "文件上传---- " + response.body());
                            try {
                                UploadBean bean = getGson().fromJson(response.body(), UploadBean.class);
                                if (bean.getCode() == 0){
                                    finish();
                                }

                                ToastUtil.showToast(bean.getMessage());
                            } catch (Exception e) {

                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            Log.e("TAG", "onError---- " + response.message());
                        }
                    });
        }
    }


    private String getFileNameByUri(Context context, Uri uri)
    {
        String filepath = "";//default fileName
        //Uri filePathUri = uri;
        File file;
        if (uri.getScheme().toString().compareTo("content") == 0)
        {
            Cursor cursor = context.getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.ORIENTATION }, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            cursor.moveToFirst();

            String mImagePath = cursor.getString(column_index);
            cursor.close();
            filepath = mImagePath;

        }
        else if (uri.getScheme().compareTo("file") == 0)
        {
            try
            {
                file = new File(new URI(uri.toString()));
                if (file.exists())
                    filepath = file.getAbsolutePath();

            }
            catch (URISyntaxException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else
        {
            filepath = uri.getPath();
        }
        return filepath;
    }
}
